package com.zlmediakit.zlmwebrtc;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;


import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.SessionDescription;
import org.webrtc.SurfaceViewRenderer;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author Kyle
 * @explain 播放
 * @creat 2022/6/25 23:38
 */
public class ZLMediaKitPlayer extends Activity {
    private String TAG=getClass().getSimpleName();
    private SurfaceViewRenderer surfaceViewRendererRemote;
    private EditText et_url;
    private WebRtcWrapper webRtcWrapper;
    private PeerConnection remotePeerConnection;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zlm_player);
        et_url=findViewById(R.id.et_url);
        webRtcWrapper=new WebRtcWrapper(getApplicationContext(),true);
        surfaceViewRendererRemote=findViewById(R.id.surfaceViewRendererRemote);
        surfaceViewRendererRemote.init(webRtcWrapper.getEglBaseContext(), null);
        remotePeerConnection=webRtcWrapper.createRemotePeerConnection(new WebRtcWrapper.SimplePeerConnectionObserver("remotePeerConnection"){
            @Override
            public void onAddStream(MediaStream mediaStream) {
                super.onAddStream(mediaStream);
                if(mediaStream.videoTracks.size()>0){
                    mediaStream.videoTracks.get(0).addSink(surfaceViewRendererRemote);
                }
            }
        });
    }

    public void createOffer(View view){
        MediaConstraints mediaConstraints = new MediaConstraints();
        remotePeerConnection.createOffer(new WebRtcWrapper.SimpleSdpObserver("createOffer"){
            @Override
            public void onCreateSuccess(SessionDescription sessionDescription) {
                super.onCreateSuccess(sessionDescription);
                remotePeerConnection.setLocalDescription(new WebRtcWrapper.SimpleSdpObserver("local"){
                    @Override
                    public void onSetSuccess() {
                        super.onSetSuccess();
                        sendOfferToZlm(sessionDescription.description);
                    }
                },sessionDescription);
            }
        },mediaConstraints);
    }

    private void sendOfferToZlm(String sdp){
        Log.e(TAG,"sendOfferToZlm:"+sdp);
        OkHttpClient okHttpClient=new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"),sdp);
        Request.Builder builder = new Request.Builder();
        final Request request = builder.url(et_url.getText().toString()).post(body).build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "request error:"+e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "response ----->" + result);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String answer=jsonObject.getString("sdp");
                    handleRemoteSDP(answer);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void handleRemoteSDP(String sdpStr){
        remotePeerConnection.setRemoteDescription(new WebRtcWrapper.SimpleSdpObserver("handleRemoteSDP")
                ,new SessionDescription(SessionDescription.Type.ANSWER, sdpStr));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(remotePeerConnection!=null){
            remotePeerConnection.close();
        }
        surfaceViewRendererRemote.release();
        webRtcWrapper.release();
    }
}
